<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <el-col :span="isHide ? 1 : 6" :xs="24" class="relative">
        <div class="app-container-tree-border">
          <project-tree-select-inner class="cd-mb8" :projectId="projectId" @changeProject="changeProject" />
          <el-tree :data="treeList" :props="defaultProps" ref="tree" node-key="id" highlight-current
            @node-click="handleNodeClick">
            <div slot-scope="{node, data}" class="custom-tree-node" :title="node.label" v-text="node.label"
              :class="{ 'red': data.type == 'zd' && data.jlg == 0 }"></div>
          </el-tree>
          <div class="tree-hide-button iconfont" :class="isHide ? 'icon-xiangyou' : 'icon-xiangzuo'"
            @click="() => { isHide = !isHide }">
          </div>
        </div>
      </el-col>
      <el-col :span="isHide ? 23 : 18" :xs="24">
        <div class="app-container-table-border" v-show="treeInfo.type == 'zd'">
          <div class="header-title">
            <span>第</span>
            <el-select class="cd-ml8 cd-mr8" v-model="queryParams.qsId" placeholder="" size="mini" style="width: 60px;"
              @change="qsChange">
              <el-option :class="{ 'red': item.hasJl == 0 }" v-for="item in qsOptions" :key="item.qsId"
                :label="item.settleIndex" :value="item.qsId"></el-option>
            </el-select>
            <span>期计量列表</span>
          </div>
          <el-row :gutter="10" class="mb8 top-right-btn small-line-height">
            <el-col :span="1.5">
              <el-button type="primary" plain size="mini" @click="handleAdd" :disabled="!canOperation()"
                v-hasPermi="['cm:baSettleDeductDetail:add']">新增</el-button>
            </el-col>
          </el-row>
          <el-table border stripe v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
            :max-height="tableHeight">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="申请时间" align="center" prop="deductTime" width="120">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.deductTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="款项类型" align="center" prop="deductType" min-width="100">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.deduct_type" :value="scope.row.deductType" />
              </template>
            </el-table-column>
            <el-table-column label="款项金额" align="center" prop="deductDetailMoney" min-width="120" />
            <el-table-column label="附件" header-align="center" prop="remark" min-width="160" show-overflow-tooltip>
              <template slot-scope="scope">
                <div class="file-border pointer theme-color" v-for="(item, index) in scope.row.fileList" :key="index"
                  @click="download(item)">
                  <span class="el-icon-document cd-mr4"></span>
                  <span class="pointer theme-color">{{ item.originalName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="款项备注" align="center" prop="remark" min-width="120" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['cm:baSettleDeductDetail:edit']" :disabled="!canOperation()">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['cm:baSettleDeductDetail:remove']" :disabled="!canOperation()">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
        <div class="app-container-table-border" v-show="treeInfo.type == 'bd'">
          <el-table border stripe v-loading="loading" :data="dataList" :summary-method="getSummaries2" show-summary
            :max-height="tableHeight2" :span-method="spanMethod">
            <el-table-column label="站点名称" align="center" property="zdName" min-width="160" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.zdName || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="期数" align="center" property="qs" min-width="140" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.qs || "-" }}</span>
                <!--                <span>第{{ scope.row.qs || "-" }}期</span>-->
              </template>
            </el-table-column>
            <el-table-column label="奖罚金额" align="center" property="jfje" min-width="140" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.jfje || "0.00" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="扣回开工预付款" align="center" property="khkgyfk" min-width="140">
              <template slot-scope="scope">
                <span>{{ scope.row.khkgyfk || "0.00" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="多开票金额" align="center" property="dkp" min-width="140">
              <template slot-scope="scope">
                <span>{{ scope.row.dkp || "0.00" }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <!-- 添加或修改其他计量详情对话框 -->
    <jy-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="申请日期" prop="deductTime">
          <el-date-picker clearable v-model="form.deductTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择申请日期" style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="款项类型" prop="deductType">
          <el-select v-model="form.deductType" placeholder="请选择款项类型" style="width: 100%;">
            <el-option v-for="dict in dict.type.deduct_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="款项金额" prop="deductDetailMoney">
          <el-input type="number" v-model="form.deductDetailMoney" placeholder="请输入款项金额" />
        </el-form-item>
        <el-form-item label="附件" prop="fileNo">
          <fileUpload v-model="form.fileNo" :oldList="form.fileNoOld" :disabled="isDisabled" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </jy-dialog>
  </div>
</template>

<script>
import { listBaSettleDeductDetail, listBaSettleDeductDetailByBd, getBaSettleDeductDetail, delBaSettleDeductDetail, addBaSettleDeductDetail, updateBaSettleDeductDetail } from "@/api/cm/baSettleDeductDetail";
import { listBsQs } from "@/api/cm/bsQs";
import { queryReportStatus } from "@/api/cm/reportForm";
import { queryBdTree } from "@/api/base/bsBd";
import { mapGetters } from "vuex";
import decimal from "@/utils/big-decimal";

export default {
  name: "BaSettleDeductDetail",
  dicts: ['deduct_type'],
  data () {
    return {
      isHide: false,
      treeList: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      qsOptions: [],
      // 其他计量详情表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isDisabled: false,
      reportStatus: '',// 报表状态
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        qsId: undefined,
        bdId: undefined,
        zdId: undefined,
      },
      // 表单参数
      form: {},
      treeInfo: {
        type: 'zd'
      },
      // 表单校验
      rules: {
        deductTime: [
          { required: true, message: "款项时间不能为空", trigger: "blur" }
        ],
        deductType: [
          { required: true, message: "款项类型不能为空", trigger: "change" }
        ],
        deductDetailMoney: [
          { required: true, message: "款项金额不能为空", trigger: "blur" }
        ],
        // fileNo: [{ required: true, validator: this.validateFile, trigger: "blur" }],
      },
      tableHeight: document.documentElement.scrollHeight - 220,
      tableHeight2: document.documentElement.scrollHeight - 130,
    };
  },
  // 监听顶部全局下拉
  computed: {
    ...mapGetters(["sysProjectId", "sysProjectList"])
  },
  watch: {
    sysProjectId (newVal, oldVal) {
      this.changeProject(newVal);
    }
  },
  created () {
    this.changeProject();
  },
  methods: {
    changeProject (projectId = this.sysProjectId) {
      this.projectId = projectId;
      this.projectChangeResetQuery();
      // 系统顶部选中项目变化
      this.getBdTree();
    },
    getBdTree () {
      queryBdTree({ projectId: this.projectId, hasJl: 3 }).then(response => {
        this.treeList = response.data;
      });
    },
    handleNodeClick (data) {
      if (data.type == 'zd') {
        this.treeInfo = data;
        this.queryParams.zdId = data.id;
        this.queryParams.bdId = data.parentId;
        if (this.queryParams.bdId == this.queryParams.oldBdId) {
          this.qsChange();
        } else {
          // this.getQs();
        }
        this.getQs();
        this.queryParams.oldBdId = data.parentId;
      } else if (data.type == 'bd') {
        this.treeInfo = data;
        this.queryParams.bdId = data.id;
        this.getListByBd();
        // this.$modal.msgWarning("请选择站点");
        // this.queryParams.zdId = null;
        // this.$refs.tree.setCurrentKey(data.children[0].id);
      }
    },
    // 获取期数
    getQs () {
      const queryParams = {
        bdId: this.queryParams.bdId,
        zdId: this.queryParams.zdId,
        pageNum: 1,
        pageSize: 100,
        jlType: 2 // 1 中间计量 2 其他计量
      };
      listBsQs(queryParams).then(response => {
        this.qsOptions = response.rows;
        if (this.qsOptions.length > 0) {
          // 默认期数
          let qsInfo = this.qsOptions.find(item => item.currentFlag == 1);
          if (!qsInfo) {
            qsInfo = this.qsOptions[this.qsOptions.length - 1];
          }
          this.queryParams.qsId = qsInfo.qsId;
          this.qsChange();
        } else {
          this.queryParams.qsId = null;
          this.dataList = [];
          this.total = 0;
          this.reportStatus = '';
        }
      });
    },
    qsChange () {
      this.handleQuery();
      this.getReportStatus();
    },
    /** 查询其他计量详情列表(站点) */
    getList () {
      this.loading = true;
      listBaSettleDeductDetail(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询其他计量详情列表（标段） */
    getListByBd () {
      this.loading = true;
      listBaSettleDeductDetailByBd(this.queryParams).then(response => {
        this.dataList = response.data;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        settleId: undefined,
        deductDetailId: undefined,
        deductType: undefined,
        deductDetailMoney: undefined,
        remark: undefined,
        deductTime: undefined,
        fileNo: undefined,
        fileNos: [],
        fileNoOld: [],
        zdId: this.queryParams.zdId,
        bdId: this.queryParams.bdId,
        qsId: this.queryParams.qsId,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    projectChangeResetQuery () {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        qsId: undefined,
        bdId: undefined,
        zdId: undefined,
      };
      this.total = 0;
      this.dataList = [];
      this.reportStatus = '';
      this.qsOptions = [];
    },
    // 获取报表状态 00 未审核 33 已驳回  这两个状态时可编辑
    getReportStatus () {
      const query = {
        bdId: this.queryParams.bdId,
        qsId: this.queryParams.qsId
      };
      queryReportStatus(query).then(res => {
        const { status } = res.data;
        this.reportStatus = status;
      });
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.deductDetailId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    getSummaries2 (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index === 2 || index === 3 || index === 4) {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return decimal.add(prev, curr, 2);
              } else {
                return decimal.round(prev);
              }
            }, 0);
            sums[index] += '';
          } else {
            sums[index] = '';
          }
        }
      });

      return sums;
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加其他计量详情";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.loading = true;
      this.reset();
      const deductDetailId = row.deductDetailId || this.ids;
      getBaSettleDeductDetail(deductDetailId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改其他计量详情";
        if (this.form.fileNo) {
          this.form.fileNoOld = this.form.fileNo.split(',');
        }
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fileNo) {
            this.form.fileNos = this.form.fileNo.split(',');
          }
          this.buttonLoading = true;
          if (this.form.deductDetailId != null) {
            updateBaSettleDeductDetail(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addBaSettleDeductDetail(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const deductDetailIds = row.deductDetailId || this.ids;
      this.$modal.confirm('是否确认删除选中的数据项？').then(() => {
        this.loading = true;
        return delBaSettleDeductDetail(deductDetailIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('cm/baSettleDeductDetail/export', {
        ...this.queryParams
      }, `baSettleDeductDetail_${new Date().getTime()}.xlsx`);
    },
    // 下载
    async download (row) {
      this.$download.oss(row.ossId);
    },
    //合并站点名称列
    spanMethod ({ row, column, rowIndex, columnIndex }) {
      // 只对“站点名称”列进行合并
      if (columnIndex === 0) {
        let _span = 1;
        let count = 0;

        // 遍历 dataList，计算相同 zdName 出现的次数
        for (let i = 0; i < this.dataList.length; i++) {
          if (this.dataList[i].zdName === row.zdName) {
            count++;
          }
        }

        // 如果是当前组的第一个元素，则设置 rowspan，否则设置为 0（隐藏）
        if (rowIndex === 0 || this.dataList[rowIndex - 1].zdName !== row.zdName) {
          return {
            rowspan: count,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    // 是否可操作
    canOperation () {
      return this.queryParams.zdId && this.queryParams.qsId && (this.reportStatus == '00' || this.reportStatus == '33');
    }
  }
};
</script>
<style lang="scss" scoped>
.header-title {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 10px 0;
  font-size: 20px;
  font-weight: 700;
}

.file-border {
  font-size: 14px;
  width: 100%;
  overflow: hidden;
  /* 隐藏超出的内容 */
  white-space: nowrap;
  /* 不换行 */
  text-overflow: ellipsis;
}
</style>
